#include "bmppallette.h"
#include "bmppallettemanager.h"

/** draws the bitmap pallette: the long list of colored rectangles */
void BMPPallette::draw(SDL_Surface * a_surface)
{
	if(m_bmp)
	{
		char buffer[30];
		SRect r(*getArea());
		r.setHeight(m_heightPerEntry);
		r.y -= m_scroll;
		SRect box;
		SPoint textLoc;
		for(int i = m_scroll/m_heightPerEntry; i < m_colorOccurance.size(); ++i)
		{
			box = r;
	//		box.inset(ENTRY_INSET/2);
			bool insetThisBox = false;
			for(int u = 0; !insetThisBox &&
				u < BMPPalletteManager::NUM_USER_COLORS;
				++u)
			{
				if(insetThisBox = (i == *m_parent->getSelectedColorIndex(u)))
				{
					box.inset(ENTRY_INSET);
				}
			}
			box.clip(m_dimension);
			if(box.isValid())
			{
				VSDL_FillRect(a_surface, &box, 
					RGBQUAD_toSurfaceColor(*m_bmp->getColor(i), a_surface->format)
				);
				sprintf_s(buffer, sizeof(buffer), "%d", 
					m_colorOccurance.get(i));
				textLoc.set(r.getX()+ENTRY_INSET, r.getY()+ENTRY_INSET);
				if(getArea()->contains(textLoc))
					VSDL_drawString(buffer, a_surface, textLoc);
			}
			r.y += r.getHeight();
		}
	}
	//setClean();
}

bool BMPPallette::handleEvent(const SDL_Event & e)
{
	bool dirty = false;
	switch(e.type)
	{
	case SDL_MOUSEBUTTONDOWN:
		switch(e.button.button)
		{
		case SDL_BUTTON_LEFT:
		case SDL_BUTTON_RIGHT:
			{
				int offsetY = e.button.y - m_dimension.y + m_scroll;
				int clickedColor = offsetY / m_heightPerEntry;
				*m_parent->getSelectedColorIndex((e.button.button==SDL_BUTTON_LEFT)
					?BMPPalletteManager::COLOR_MAIN
					:BMPPalletteManager::COLOR_OFF) = clickedColor;
				m_parent->refresh();
				dirty = true;
			}
			break;
		case SDL_BUTTON_WHEELUP:
		case SDL_BUTTON_WHEELDOWN:
			{
				// TODO magic number...
				int scrollSpeed = m_dimension.getHeight() / 3;
				m_scroll += ((e.button.button==4)?-scrollSpeed:scrollSpeed);
				if(m_scroll < 0)
					m_scroll = 0;
				if(m_scroll > m_colorOccurance.size()*m_heightPerEntry - m_dimension.getHeight())
				{
					m_scroll = m_colorOccurance.size()*m_heightPerEntry - m_dimension.getHeight();
				}
			}
			dirty = true;
			break;
		}
		break;
	case SDL_KEYDOWN:
		switch(e.key.keysym.sym)
		{
		case SDLK_SPACE:
			{
				int transparentColor = *m_parent->getSelectedColorIndex(BMPPalletteManager::COLOR_OFF);
				*m_parent->getSelectedColorIndex(BMPPalletteManager::COLOR_TRANSPARENT) = transparentColor;
				m_parent->refresh();
				m_parent->getParent()->setDirty(0);
				dirty = true;
			}
			break;
		}
	}
	if(dirty)setDirty(0);
	return dirty;
}